/**
 * @author Created by qiush on 2017-07-04.
 */

import * as React from 'react';
import {ComponentDecorator, connect} from 'react-redux';

import store from '../store/index';
import {ActionType} from '../store/ActionType';
import util from '../common/util';

import CanvasView from '../panes/canvas/CanvasView';

import {IChildSelectionMergedProps, IChildSelectionOwnProps, mapStateToProps} from './IChildSelection';
import AbsOneChildVisiblePane from './AbsOneChildVisiblePane';

import {IView} from '../types/IView';

import './TabPane.css';

type TabTitleElement = JSX.Element | React.ReactText;

/**
 * 简单的切换的处理, 没有做动画效果, 只是直接显示当前选中的组件(如果选中的组件是这个的直接子组件的话)
 */
class TabPane extends AbsOneChildVisiblePane {
  render() {
    return (
      <div className="TabPane">
        <ul className="TabPane-titles">
          {this.renderTitles()}
        </ul>
        <div className="TabPane-contents">
          {this.renderChildren()}
        </div>
      </div>
    );
  }

  private renderTitles(): TabTitleElement[] {
    const current: number = Math.max(0, this.props.current);
    return React.Children.map(this.props.children, (child: React.ReactChild, index: number): TabTitleElement => {
      if (!util.isReactElement(child) || !child.props.view || !child.props.view.attrVals) {
        return child;
      }

      const className = `TabPane-title ${current === index ? 'TabPane-title-active' : ''}`;
      const style: React.CSSProperties = this.getTitleStyle(current, index);
      const props: React.HTMLAttributes<HTMLElement> = {
        className,
        style,
        onClick: (event: React.MouseEvent<HTMLElement>) => this.handleClick(event, child.props.view)
      };
      const titleView = child.props.view.children[0];
      return (
        <li {...props}>
          <CanvasView key={titleView.id} view={titleView} refUpdater={child.props.refUpdater}/>
        </li>
      );
    });
  }

  private getTitleStyle(current: number, childIndex: number): React.CSSProperties {
    if (current === -1) {
      return {};
    }
    if (current === childIndex) {
      return {};
    }
    return {};
  }

  private handleClick = (event: React.MouseEvent<HTMLElement>, view: IView) => {
    event.stopPropagation();

    // 点击就选中
    store.dispatch({
      type: ActionType.SELECT_VIEW,
      designId: view.designId,
      view
    });
  }

}

type TabPaneDecorator = ComponentDecorator<IChildSelectionMergedProps, IChildSelectionOwnProps>;
const componentDecorator: TabPaneDecorator = connect(mapStateToProps);
export default componentDecorator(TabPane);
